<!--
  * 门店表
  *
  * @Author:    zhoujk
  * @Date:      2025-01-26 06:40:44
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">
      <a-form-item label="门店名称" class="smart-query-form-item">
        <a-input style="width: 200px" v-model:value="queryForm.storeNameLeftLike" placeholder="请输入门店名称" />
      </a-form-item>
      <a-form-item label="登录账号" class="smart-query-form-item">
        <a-input style="width: 200px" v-model:value="queryForm.no" placeholder="请输入登录账号" />
      </a-form-item>
      <a-form-item label="状态" class="smart-query-form-item">
        <SmartEnumSelect width="200px" v-model:value="queryForm.status" enumName="ZZB_ENABLE_STATUS_ENUM" placeholder="请选择状态" />
      </a-form-item>
      <a-form-item class="smart-query-form-item">
        <a-button type="primary" @click="onSearch">
          <template #icon>
            <SearchOutlined />
          </template>
          查询
        </a-button>
        <a-button @click="resetQuery" class="smart-margin-left10">
          <template #icon>
            <ReloadOutlined />
          </template>
          重置
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button @click="showForm" type="primary" size="small" v-privilege="'store:insert'">
          <template #icon>
            <PlusOutlined />
          </template>
          新建
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <!-- <TableOperator v-model="columns" :tableId="null" :refresh="queryData" /> -->
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->

    <!---------- 表格 begin ----------->
    <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered :loading="tableLoading" :pagination="false">
      <template #bodyCell="{ text, record, column }">
        <!-- 有图片预览时 注释解开并把下面的'picture'修改成自己的图片字段名即可 -->
        <!-- <template v-if="column.dataIndex === 'picture'">
            <FilePreview :fileList="text" type="picture" />
          </template> -->

        <!-- 使用字典时 注释解开并把下面的'data-dictionaries'修改成自己的字典字段名即可 有多个字典字段就复制多份同理修改 不然不显示字典 -->
        <!-- 方便修改tag的颜色 orange green purple success processing error default warning -->
        <!-- <template v-if="column.dataIndex === 'data-dictionaries'">
          <a-tag color="cyan">
            {{ text && text.length > 0 ? text.map((e) => e.valueName).join(',') : '暂无' }}
          </a-tag>
        </template> -->

        <template v-if="column.dataIndex === 'status'">
          <a-tag :color="statusTypeColorArray[text]">{{ $smartEnumPlugin.getDescByValue('ZZB_ENABLE_STATUS_ENUM', text) }}</a-tag>
        </template>

        <template v-if="column.dataIndex === 'action'">
          <div class="smart-table-operate">
            <a-button @click="showForm(record)" type="link" v-privilege="'store:update'">编辑</a-button>
            <a-button @click="showDetail(record)" type="link" v-privilege="'store:find_id'">查看</a-button>
            <a-button @click="resetPwd(record)" type="link" v-privilege="'store:reset_pwd'">密码重置</a-button>
            <a-button @click="downloadChange(record)" type="link">码牌激活下载</a-button>
            <a-button @click="viewMpImg(record)" type="link">码牌预览</a-button>
          </div>
        </template>
      </template>
    </a-table>
    <!---------- 表格 end ----------->

    <div class="smart-query-table-page">
      <a-pagination
        showSizeChanger
        showQuickJumper
        show-less-items
        :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :defaultPageSize="queryForm.pageSize"
        v-model:current="queryForm.pageNo"
        v-model:pageSize="queryForm.pageSize"
        :total="total"
        @change="queryData"
        @showSizeChange="queryData"
        :show-total="(total) => `共${total}条`"
      />
    </div>

    <StoresForm ref="formRef" @reloadList="queryData" />
    <StoresDetail ref="detailRef" @reloadList="queryData" />
    <ResetPwdModal ref="resetPwdRef" @success="queryData" :apiFunction="storeApi.resetPwd" />
  </a-card>

  <!-- 预览二维码 -->
  <a-modal v-model:open="openImg" title="二维码预览" :footer="false">
    <div style="text-align: center" class="m-t-10">
      <canvas id="qrCanvas" width="300" height="330"></canvas>
    </div>
  </a-modal>
</template>
<script setup>
  import { reactive, ref, onMounted, nextTick } from 'vue'
  import { message, Modal } from 'ant-design-vue'
  import { SmartLoading } from '/@/components/framework/smart-loading'
  import { storeApi } from '/@/api/business/b-merchant/store/store-api'
  import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const'
  import { smartSentry } from '/@/lib/smart-sentry'
  import TableOperator from '/@/components/support/table-operator/index.vue'
  import StoresForm from './store-form.vue'
  import StoresDetail from './store-detail.vue'
  import SmartEnumSelect from '/@/components/framework/smart-enum-select/index.vue'
  // import ResetPwdModal from './reset-pwd-modal.vue'
  import ResetPwdModal from '/@/components/business/comment/reset-pwd-modal.vue'
  import { codeApi } from '/@/api/business/b-agent/code/code-api.js'
  //import FilePreview from '/@/components/support/file-preview/index.vue'; // 图片预览组件

  // ---------------------------- 表格列 ----------------------------
  const statusTypeColorArray = ['red', 'blue']

  const columns = ref([
    {
      title: '登录账号',
      dataIndex: 'no',
      ellipsis: true,
    },
    {
      title: '门店名称',
      dataIndex: 'storeName',
      ellipsis: true,
    },
    {
      title: '城市',
      dataIndex: 'areaCode',
      ellipsis: true,
    },
    {
      title: '地址',
      dataIndex: 'addr',
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      ellipsis: true,
    },
    {
      title: '名字',
      dataIndex: 'name',
      ellipsis: true,
    },
    {
      title: '电话',
      dataIndex: 'phone',
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      width: 180,
    },
  ])

  // ---------------------------- 查询数据表单和方法 ----------------------------

  const queryFormState = {
    storeNameLeftLike: undefined, //门店名称
    no: undefined, //登录账号
    status: undefined, //状态
    pageNo: 1,
    pageSize: 10,
  }
  // 查询表单form
  const queryForm = reactive({ ...queryFormState })
  // 表格加载loading
  const tableLoading = ref(false)
  // 表格数据
  const tableData = ref([])
  // 总数
  const total = ref(0)

  // 重置查询条件
  function resetQuery() {
    let pageSize = queryForm.pageSize
    Object.assign(queryForm, queryFormState)
    queryForm.pageSize = pageSize
    queryData()
  }

  // 搜索
  function onSearch() {
    queryForm.pageNo = 1
    queryData()
  }

  // 查询数据
  async function queryData() {
    tableLoading.value = true
    try {
      let queryResult = await storeApi.page(queryForm)
      tableData.value = queryResult.data
      total.value = queryResult.total
    } catch (e) {
      smartSentry.captureError(e)
    } finally {
      tableLoading.value = false
    }
  }

  onMounted(queryData)

  // ---------------------------- 添加/修改 ----------------------------
  const formRef = ref()

  function showForm(data) {
    formRef.value.show(data)
  }

  // ---------------------------- 详情 ----------------------------
  const detailRef = ref()

  function showDetail(data) {
    detailRef.value.show(data)
  }

  // ---------------------------- 重置密码 ----------------------------
  const resetPwdRef = ref()
  async function resetPwd(record) {
    if (!resetPwdRef.value) {
      message.error('组件未加载完成，请稍后重试')
      return
    }
    resetPwdRef.value.show(record)
  }

  // ---------------------------- 二维码码牌激活下载 ----------------------------
  const downloadChange = async (record) => {
    // console.log('record==>', record)
    const params = {
      merchantId: record.merchantId,
      storeId: record.id,
    }
    await codeApi.downloadActive(params).then((res) => {
      const url = res.data.urlBase64Image
      //下载
      const link = document.createElement('a')
      link.href = url
      link.download = res.data.code + '.png'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    })
  }
  // ---------------------------- 二维码码牌预览 ----------------------------
  const openImg = ref(false)
  const imgUrl = ref('')
  const storeName = ref('')
  const viewMpImg = async (record) => {
    // console.log('record==>', record)
    storeName.value = record.storeName
    const params = {
      merchantId: record.merchantId,
      storeId: record.id,
    }
    await codeApi.downloadActive(params).then((res) => {
      imgUrl.value = res.data.urlBase64Image
      openImg.value = true
      console.log('imgUrl1==>', imgUrl.value)
      // 使用 nextTick 确保 DOM 更新完成后再调用 makeCanvas
      nextTick(() => {
        makeCanvas()
      })
    })
  }
  const makeCanvas = () => {
    // 直接执行 canvas 操作，不等待 DOMContentLoaded 事件
    const canvas = document.getElementById('qrCanvas')
    const ctx = canvas.getContext('2d')

    // 绘制红色背景
    ctx.fillStyle = '#B81614'
    ctx.fillRect(0, 0, canvas.width, canvas.height)

    // 二维码相关配置和绘制
    const qrSize = 200 // Size of the QR code within the canvas
    const qrMargin = 50
    const qrImage = new Image()
    qrImage.src = imgUrl.value //qrCode.createDataURL(4) // Scale factor for QR code image

    qrImage.onload = function () {
      // 绘制白色方块和二维码
      ctx.fillStyle = 'white'
      ctx.fillRect(qrMargin, qrMargin, qrSize, qrSize) // White square to contain QR code
      ctx.drawImage(qrImage, qrMargin, qrMargin, qrSize, qrSize)

      // 绘制四个角的装饰线条
      drawCornerLs(ctx, 40, 40, qrSize + 20, qrSize + 20, 20)

      // 添加门店文本信息
      ctx.fillStyle = '#fff'
      ctx.font = 'bold 16px Arial'
      ctx.textAlign = 'center'
      ctx.fillText(`门店:${storeName.value}`, canvas.width / 2, canvas.height - 30)
    }

    /**
     * 绘制四个角的L形（开口朝中间）
     * @param {CanvasRenderingContext2D} ctx - Canvas绘图上下文
     * @param {number} x - 容器左上角x坐标
     * @param {number} y - 容器左上角y坐标
     * @param {number} width - 容器宽度
     * @param {number} height - 容器高度
     * @param {number} length - L形每条边的长度（向中间延伸的距离）
     * @param {string} [color='#fff'] - 线段颜色（默认白色）
     * @param {number} [lineWidth=3] - 线段宽度（默认3像素）
     */
    function drawCornerLs(ctx, x, y, width, height, length, color = '#fff', lineWidth = 3) {
      // 配置绘图样式（线帽设为'square'让L形角更整齐）
      ctx.strokeStyle = color
      ctx.lineWidth = lineWidth
      ctx.lineCap = 'square'

      // ---- 1. 左上角L形（上边+左边，开口向右下）----
      ctx.beginPath()
      ctx.moveTo(x, y) // 起点：左上角顶点
      ctx.lineTo(x + length, y) // 上边：向右延伸length
      ctx.moveTo(x, y) // 回到起点
      ctx.lineTo(x, y + length) // 左边：向下延伸length
      ctx.stroke()

      // ---- 2. 右上角L形（上边+右边，开口向左下）----
      ctx.beginPath()
      ctx.moveTo(x + width, y) // 起点：右上角顶点
      ctx.lineTo(x + width - length, y) // 上边：向左延伸length
      ctx.moveTo(x + width, y) // 回到起点
      ctx.lineTo(x + width, y + length) // 右边：向下延伸length
      ctx.stroke()

      // ---- 3. 右下角L形（右边+下边，开口向左上）----
      ctx.beginPath()
      ctx.moveTo(x + width, y + height) // 起点：右下角顶点
      ctx.lineTo(x + width, y + height - length) // 右边：向上延伸length
      ctx.moveTo(x + width, y + height) // 回到起点
      ctx.lineTo(x + width - length, y + height) // 下边：向左延伸length
      ctx.stroke()

      // ---- 4. 左下角L形（下边+左边，开口向右上）----
      ctx.beginPath()
      ctx.moveTo(x, y + height) // 起点：左下角顶点
      ctx.lineTo(x + length, y + height) // 下边：向右延伸length
      ctx.moveTo(x, y + height) // 回到起点
      ctx.lineTo(x, y + height - length) // 左边：向上延伸length
      ctx.stroke()
    }
  }
</script>
